<template>
  <div style="background-color: lightcyan">
    <el-card style="width: 50%; margin-left: 364px;">
      <el-form :model="userInfo">
        <div style="margin: 10px; text-align: center">
<!--          <el-upload
            :disabled = "canmodify"
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="userInfo.avatar != null" :src="userInfo.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>-->
          <el-upload :disabled = "canmodify" class="avatar-uploader" action="http://localhost:8080/file/uploadimage"
                     :on-success="handleAvatarSuccess" :file-list="[]">
            <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </div>
        <el-form-item label="姓名" label-width="80px" style="padding-right: 20px">
          <el-input v-model="userInfo.realName" disabled></el-input>
        </el-form-item>
        <el-form-item label="网名" label-width="80px" style="padding-right: 20px">
          <el-input v-model="userInfo.userName" :disabled = "canmodify"></el-input>
        </el-form-item>
        <el-form-item label="性别" label-width="80px" style="padding-right: 20px">
          <el-radio-group v-model="sex" :disabled = "canmodify">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
            <el-radio label="保密"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="邮箱" label-width="80px" style="padding-right: 20px">
          <el-input v-model="userInfo.email" :disabled = "canmodify"></el-input>
        </el-form-item>
        <el-form-item label="电话" label-width="80px" style="padding-right: 20px">
          <el-input v-model="userInfo.phoneNumber" :disabled = "canmodify"></el-input>
        </el-form-item>
        <el-form-item label="学校" label-width="80px" style="padding-right: 20px">
          <el-select v-model="userInfo.schoolId" placeholder="请选择学校" @change="onSchoolChange" @focus="refreshSchoolList" :disabled = "canmodify" filterable>
            <el-option v-for="item in schoolList" :key="item.schoolId" :value="item.schoolId"
                       :label="item.schoolName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级" label-width="80px" style="padding-right: 20px">
          <el-select v-model="userInfo.classId" placeholder="请选择班级" @change="onClassChange" @focus="refreshClassList(userInfo.schoolId)" :disabled = "canmodify" filterable>
            <el-option v-for="item in classList" :key="item.classId" :value="item.classId"
                       :label="item.className"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="userInfo.userType === 0" label="班级" label-width="80px" style="padding-right: 20px">
          <el-input v-model="userInfo.className" :disabled = "canmodify"></el-input>
        </el-form-item>
        <el-form-item :label="idName" label-width="80px" style="padding-right: 20px">
          <el-input v-model="userInfo.userId" :disabled = "canmodify"></el-input>
        </el-form-item>
        <div style="text-align: center; margin-bottom: 20px">
          <div v-if="modifying" style="margin-left: 50px">
            <el-button style="padding-left: 80px; padding-right: 80px; margin-right: 50px"  v-if="modifying" type="primary" @click="updateUserInfo">保存</el-button>
            <el-button style="padding-left: 66px; padding-right: 66px" v-if="modifying" type="warning" @click="cancelUpdateUserInfo">取消修改</el-button>
          </div>
          <el-button  style="margin-left: 60px; padding-left: 170px; padding-right: 170px;" v-else type="danger" @click="changeModifyingStatus">我要修改</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {getClassInfoList, getSchoolInfoList, updateUserInfo} from '../../request/api'

export default {
  name: 'UserProfile',
  data () {
    return {
      userInfo: null,
      sex: null,
      schoolList: [
        {
          schoolId: null,
          schoolName: null
        }
      ],
      classList: [
        {
          classId: null,
          className: null
        }
      ],
      canmodify: true,
      modifying: false,
      idName: null
    }
  },
  methods: {
    refreshSchoolList: function () {
      console.log('刷新学校信息列表')
      getSchoolInfoList('/user/getSchoolList').then(resp => {
        if (resp.responseCode === 20007) {
          this.schoolList = resp.data
        } else {
          console.log(JSON.stringify(resp))
        }
      })
    },
    refreshClassList: function (schoolId) {
      console.log(this.userInfo)
      if (schoolId === null) {
        return
      }
      console.log(schoolId)
      console.log('刷新班级信息列表')
      getClassInfoList('/user/getClassList', schoolId).then(resp => {
        if (resp.responseCode === 20007) {
          this.classList = resp.data
          console.log(this.classList)
        } else {
          console.log(JSON.stringify(resp))
        }
      })
    },
    // 学校选择变化的事件处理函数
    onSchoolChange: function () {
      /* console.log('学校名称修改')
      console.log(this.userInfo) */
      const tempUser = JSON.parse(sessionStorage.getItem('userInfo'))
      console.log(tempUser)
      if (tempUser.schoolId === this.userInfo.schoolId) {
        return
      } else {
        this.userInfo.classId = null
        this.userInfo.className = null
      }
      if (this.userInfo.schoolId === null) {
        this.userInfo.schoolId = null
        this.userInfo.schoolName = null
        this.userInfo.classId = null
        this.userInfo.className = null
      }
      // 在学校列表中找到选择的学校
      const selectedSchool = this.schoolList.find(item => item.schoolId === this.userInfo.schoolId)
      /* console.log('找到学校')
      console.log(selectedSchool) */

      // 如果找到了选择的学校，则更新 userInfo 对象中的学校名字
      if (selectedSchool) {
        this.userInfo.schoolName = selectedSchool.schoolName
      }
    },
    // 班级选择变化的事件处理函数
    onClassChange: function () {
      const tempUser = JSON.parse(sessionStorage.getItem('userInfo'))
      if (tempUser.classId === this.userInfo.classId) {
        return
      } else if (this.userInfo.classId === null) {
        this.userInfo.className = null
        return
      }
      // 在学校列表中找到选择的学校
      const selectedClass = this.classList.find(item => item.classId === this.userInfo.classId)

      // 如果找到了选择的学校，则更新 userInfo 对象中的学校名字
      if (selectedClass) {
        this.userInfo.className = selectedClass.className
      }
      console.log(this.userInfo)
    },
    handleAvatarSuccess (response, file, filelsit) {
      if (response.responseCode === 20012) {
        this.userInfo.avatar = response.data
        console.log('上传的图片url' + response.data)
      } else {
        this.$message.error({
          message: response.msg,
          duration: 3000
        })
      }
      console.log(response)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    updateUserInfo: function () {
      if (this.sex === '男') {
        this.userInfo.sex = 0
      } else {
        this.userInfo.sex = this.sex === '女' ? 1 : 2
      }
      updateUserInfo('/user/updateUserInfo', this.userInfo).then(resp => {
        if (resp.responseCode === 20008) {
          sessionStorage.setItem('userInfo', resp.data)
          this.$message({
            message: '修改信息成功',
            type: 'success',
            duration: 3000
          })
          this.handleUserInfoChange(resp.data)
          this.changeModifyingStatus()
        } else if (resp.responseCode === 1005 || resp.responseCode === 1006) {
          this.$message.error({
            message: resp.message,
            duration: 3000
          })
        } else {
          this.$message({
            message: '服务器内部异常，请稍后再试',
            type: 'warning',
            duration: 3000
          })
        }
      })
    },
    handleUserInfoChange (updatedUserInfo) {
      // 当用户信息发生变化时，触发自定义事件
      sessionStorage.setItem('userInfo', JSON.stringify(updatedUserInfo))
      console.log('当用户信息发生变化时，触发自定义事件')
      console.log(updatedUserInfo)
      this.$emit('update-user-info', updatedUserInfo)
    },
    changeModifyingStatus: function () {
      this.modifying = this.canmodify
      this.canmodify = !this.canmodify
    },
    cancelUpdateUserInfo: function () {
      this.userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
      this.changeModifyingStatus()
      if (this.userInfo === null || this.userInfo.sex === null || this.userInfo.sex === 2) {
        this.sex = '保密'
      } else {
        this.sex = this.userInfo.sex === 0 ? '男' : '女'
      }
    }
  },
  created () {
    this.userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
    if (this.userInfo === null || this.userInfo.sex === null || this.userInfo.sex === 2) {
      this.sex = '保密'
    } else {
      this.sex = this.userInfo.sex === 0 ? '男' : '女'
    }
    this.idName = this.userInfo.userType === 0 ? '工号' : '学号'
    this.refreshSchoolList()
    if (this.userInfo.schoolId !== null) {
      this.refreshClassList(this.userInfo.schoolId)
    }
  }
}
</script>

<style scoped>
/deep/ .el-form-item__label {
  font-weight: bold;
}
/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
/deep/ .avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
/deep/ .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border-radius: 50%;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border-radius: 50%;
}
/deep/ .el-upload{
  border-radius: 50% !important;
}
</style>
